using Godot;
using System;
using System.Collections.Generic;

public partial class TimePeriodManager : Node
{
	[Signal]
	public delegate void TimePeriodFinishedEventHandler(string periodName);

	// Private variables
	private class TimeClock(double period)
    {
		private double _timetick = 0.0;
		private double _period = period;
		private bool _started = false;

        public bool Check()
		{
			return _timetick >= _period;
		}

		public void Update(double delta)
		{
			if (_started && _timetick < _period) _timetick += delta;
		}

		public void Start()
		{
			Reset();
			_started = true;
		}

		public void Reset()
		{
			_started = false;
			_timetick = 0.0;
		}

		public void Change(double period) { _period = period; }

		public double Current() { return _timetick; }
	}

	private Dictionary<string, TimeClock> _periods;


	public TimePeriodManager()
	{
		_periods = new Dictionary<string, TimeClock>();
	}


	// Public interfaces
	public void RegisterTimePeriod(string periodName, double timePeriod)
	{
		_periods.Add(periodName, new TimeClock(timePeriod));
	}

	public void StartTimePeriod(string periodName)
	{
		_periods[periodName].Start();
	}

	public void InterruptTimePeriod(string periodName)
	{
		_periods[periodName].Reset();
	}

	public void EditTimePeriod(string periodName, double timePeriod)
	{
		_periods[periodName].Change(timePeriod);
	}

	// GODOT - Process
	public override void _Process(double delta)
	{
		foreach(var kvp in _periods)
		{
			if (kvp.Value.Check())
			{
				EmitSignal(SignalName.TimePeriodFinished, kvp.Key);
				kvp.Value.Reset();
			}
			else
			{
				kvp.Value.Update(delta);
			}
		}
	}
}
